<?php

namespace services\system;

use api\modules\common\services\UploadService;
use api\modules\v1\forms\system\SystemConfigForm;
use common\components\Service;
use common\helpers\RedisHelper;
use common\models\sys\SysFile;
use common\models\system\SystemConfig;
use services\log\LogMemberOpService;
use services\sys\SysFileService;
use Yii;

class SystemConfigService extends Service
{
    /**
     * 获取小程序首页配置信息
     * @param string $mobile
     * @return void
     * @throws \Exception
     */
    public static function getMiniIndex(): array
    {
        $keys = SystemConfig::$wxMiniKeys;
        $data = self::getConfigFormat($keys);
        $data[SystemConfig::NAME_C_HOME_PAGE_BANNER_IMAGE] = array_column($data[SystemConfig::NAME_C_HOME_PAGE_BANNER_IMAGE], 'file_url');
        $data[SystemConfig::NAME_C_HOME_PAGE_BANNER_VIDEO] = $data[SystemConfig::NAME_C_HOME_PAGE_BANNER_VIDEO]['file_url'];

        return [
            'title' => $data[SystemConfig::NAME_C_HOME_PAGE_TITLE],
            'type' => $data[SystemConfig::NAME_C_HOME_PAGE_BANNER_TYPE],
            'image' => $data[SystemConfig::NAME_C_HOME_PAGE_BANNER_IMAGE],
            'video' => $data[SystemConfig::NAME_C_HOME_PAGE_BANNER_VIDEO],
            'content' => $data[SystemConfig::NAME_C_HOME_PAGE_BANNER_CONTENT],
        ];
    }

    /**
     * 微信首页配置信息
     * @return array
     */
    public function getWxMiniConfigInfo(): array
    {
        return array_merge(self::getConfigFormat(SystemConfig::$wxMiniKeys), [
            'image_type' => UploadService::$imageTypeArr,
            'video_type' => UploadService::$videoTypeArr,
        ]);
    }

    /**
     * 格式化配置数据
     * @param array $keys
     * @return array
     */
    public static function getConfigFormat(array $keys): array
    {
        $data = SystemConfig::find()
            ->select(['name', 'value'])
            ->where(['name' => $keys])
            ->indexBy('name')
            ->asArray()
            ->all();
        foreach ($keys as $key) {
            switch ($key) {
                case SystemConfig::NAME_C_HOME_PAGE_BANNER_TYPE:
                    $data[$key] = intval($data[$key]['value'] ?? SystemConfig::NAME_C_HOME_PAGE_BANNER_TYPE_IMG);
                    break;
                case SystemConfig::NAME_C_HOME_PAGE_BANNER_IMAGE:
                    $data[$key] = json_decode($data[$key]['value'] ?? '[]', true);
                    $format = [];
                    foreach ($data[$key] as $file) {
                        $format[] = [
                            'file' => $file,
                            'file_url' => UploadService::getFileTrueUrl(SysFile::SITE_WX_MINI, SysFile::MODULE_WX_MINI_IMG, $file),
                        ];
                    }
                    $data[$key] = $format;
                    break;
                case SystemConfig::NAME_C_HOME_PAGE_BANNER_VIDEO:
                    $file = $data[$key]['value'] ?? '';
                    $format = [
                        'file' => $file,
                        'file_url' => UploadService::getFileTrueUrl(SysFile::SITE_WX_MINI, SysFile::MODULE_WX_MINI_VIDEO, $file),
                    ];
                    $data[$key] = $format;
                    break;
                default:
                    $data[$key] = $data[$key]['value'] ?? '';
                    break;
            }
        }
        return $data;
    }

    /**
     * 编辑系统配置
     * @param SystemConfigForm $model
     * @return array
     */
    public function editWxMini(SystemConfigForm $model): array
    {
        try {
            $transaction = Yii::$app->db->beginTransaction();

            $names = $model->scenarios()[$model->getScenario()];
//            $names = array_keys(SystemConfig::$names);
            foreach ($names as $name) {
                // 1.编辑考勤配置
                $systemConfig = SystemConfig::findOne(['name' => $name]);
                if (empty($systemConfig)) {
                    $oldValue = '';
                    $systemConfig = new SystemConfig();
                    $systemConfig->name = $name;
                } else {
                    $oldValue = $systemConfig->value;
                }
                $systemConfig->value = $name == SystemConfig::NAME_C_HOME_PAGE_BANNER_IMAGE ? json_encode($model->$name) : (string)$model->$name;
                $systemConfig->desc = SystemConfig::$names[$name] ?? '';
                $systemConfig->saveAndCheckResult();

                // 2.更新文件信息
                if ($name == SystemConfig::NAME_C_HOME_PAGE_BANNER_IMAGE) {
                    $oldValue = $oldValue ?: '';
                    $oldValueFormat = $oldValue ? json_decode($oldValue, true) : [];
                    $delImageFiles = array_diff($oldValueFormat, $model->$name);
                    $addImageFiles = array_diff($model->$name, $oldValueFormat);
                    SysFileService::editFile(SysFile::SITE_WX_MINI, SysFile::MODULE_WX_MINI_IMG, $addImageFiles, $delImageFiles);
                } elseif ($name == SystemConfig::NAME_C_HOME_PAGE_BANNER_VIDEO) {
                    SysFileService::editFile(SysFile::SITE_WX_MINI, SysFile::MODULE_WX_MINI_VIDEO, $systemConfig->value, $oldValue);
                }

                // 3.操作日志
                LogMemberOpService::createSystemConfigLog($systemConfig, $systemConfig->value, $oldValue);
            }

            $transaction->commit();

            // 3.删除配置缓存
            RedisHelper::delSystemConfig($names);
            return [];
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    }

}